/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    useTheme,
    Button,
    useToast,
    Text,
    IconButton,
    IconArrowLeft,
    Container,
    InputLine,
    SuffixInput,
    CommitInput,
    VerticalMenu, DdMenuItem, TwoHalfRightPanel
} from "customize-easy-ui-component";
import { InternalItemHandResult, OriginalViewProps, } from "./common/base";
import { Link as RouterLink } from "../routing/Link";
import { EditStorageContext } from "./StorageContext";
import {ContainLine, TransparentInput} from "../comp/base";
import useOriginalDataMutation from "./useOriginalDataMutation";
import useFlowToMutation from "./useFlowToMutation";


interface FlowSelectProps {
    prepared: {
        //数据
        source: any;
        //原始记录的模板：
        template: React.ReactElement<React.ForwardRefRenderFunction<InternalItemHandResult,OriginalViewProps>>;
    }
    routeData: any;
    children: React.ReactNode;
}
//是 右边半边页面的！，编辑，或原始记录的查看：
export const FlowSelect = ({routeData,
    prepared:{source, template},
    children,
    ...other
 }: FlowSelectProps) => {
    console.log("RecordStarter捕获,切花个source=", source,"routeData=",routeData,"template",template);
  const theme = useTheme();
  const toast = useToast();
  //初始化不可以直接取React.useState(source || {})，不然路由器切换就变成旧source。新修改被抛弃了。
  const {storage, } =React.useContext(EditStorageContext) as any;

    // const {call:updateFunc,doing,result, called, reset}= useOriginalDataMutation();
    const {call:flowToFunc,doing:flowing,result, called:flowed, reset:flowreset}= useFlowToMutation();


    const [dldays, setDldays] = React.useState<number|undefined>(3);
    const [memo, setMemo] = React.useState<string|null>();

    //const {doFunc:throttleDoConfirm, ready:confirmEnable} =useThrottle((refEditor as any)?.current?.doConfirm);

    const curFlow=sessionStorage['审批单']&&JSON.parse(sessionStorage['审批单']);
    if (!routeData.params.repId) {
    return null;
    }
    //【流转审批看见】后端流转初始化 uri= 给第一个签字人看得是  "/inspect/busId/report/RepId"
    const hrefReportE =`/report/${routeData.params.template}/ver/${routeData.params.verId}/${routeData.params.repId}/ALL`;
    const hrefReportView =`/reportView/${routeData.params.template}/ver/${routeData.params.verId}/${routeData.params.repId}?&print=1`;

  return (
      <TwoHalfRightPanel
          title={`流转报告`}
          back={
              <RouterLink href={hrefReportE}>
                  <IconButton  noBind  icon={<IconArrowLeft />}
                               variant="ghost"
                               label="后退"
                               size="md"
                               css={{
                                   marginRight: theme.spaces.sm,
                                   [theme.mediaQueries.md]: {
                                       display: "none"
                                   }
                               }}
                  />
              </RouterLink>
          }
          menu={
              <VerticalMenu>
                  <DdMenuItem label="报告流转吧"
                              onClick={(e) => {
                              }}/>
              </VerticalMenu>
          }
      >
          <Container>
              <div css={{
                  paddingBottom: theme.spaces.lg
              }}>
                  <Text variant="h5">请选择流转目的地和理由</Text>
                  <ContainLine display='当前报告流转所处阶段'>
                      <TransparentInput readOnly={true} value={`${curFlow?.fNode}`}/>
                  </ContainLine>

                  <InputLine label={`限定下一个环节等待天数:`}>
                      <SuffixInput  onSave={txt=> setDldays( Number(txt) || undefined)}
                                    type="number"  value={ dldays || ''}>元</SuffixInput>
                  </InputLine>
                  <InputLine label={`流转的说明理由:`}>
                      <CommitInput  value={ memo || ''}  onSave={txt => setMemo( txt || undefined) }
                                    placeholder="如果实际收费金额比应收费任务金额少的，必须给出说明"
                      />
                  </InputLine>
              </div>
          </Container>
          { curFlow && (
              <><Button intent="primary" disabled={curFlow && !(curFlow?.entId === routeData.params.repId)}
                        onPress={async () => {
                            // '责任工程师审核'
                            const href = curFlow?.tdId ==='report_engineer_verify' ? hrefReportView : hrefReportE;
                            await flowToFunc(curFlow?.utId, routeData.params.repId, dldays || 7, href, memo || null, "YES");
                            toast({title: "流转前进一步"});
                            //签字成功与否，都将可直接清空session状态; 不支持并发进行多个审批单子或多份报告同时进入审核工作范围。一个时间点只能一条审批事项。
                            sessionStorage['审批单'] = null;
                        }}
              >
                  通过的流转下步
              </Button><Button intent="primary" disabled={!(curFlow?.entId === routeData.params.repId)}
                               onPress={async () => {
                                   await flowToFunc(curFlow?.utId, routeData.params.repId, dldays || 5, hrefReportE, memo || null, "BACK");
                                   toast({title: "回退了"});
                                   sessionStorage['审批单'] = null;
                               }}
              >
                  不行啊就后退
              </Button></>
          ) }
          { !curFlow && (
              <Text  variant="h5"　css={{ textAlign: 'center' }}>
                不在流程中，不能流转。
              </Text>
          ) }
          { result && (
              <Text  variant="h5"　css={{ textAlign: 'center' }}>
                  后端应答：{result}，请处理后再来。
              </Text>
          ) }
          <RouterLink href={"/tasks"}>
           查流程任务
          </RouterLink>

      </TwoHalfRightPanel>
  );
}


export default FlowSelect;
